package com.meb.imageexif

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import androidx.exifinterface.media.ExifInterface
import com.amap.api.maps2d.model.LatLng
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.hjq.toast.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.meb.imageexif.entity.ExifTemplateEntity
import com.meb.imageexif.event.MapEvent
import com.sugar.sugarlibrary.base.BaseActivity
import com.sugar.sugarlibrary.rx.RxEventBus
import com.sugar.sugarlibrary.rx.SugarHandleSubscriber
import com.sugar.sugarlibrary.util.image.load
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog
import kotlinx.android.synthetic.main.content_main.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : BaseActivity() {
    private var clickLatLng: LatLng? = null
    private var exif: ExifInterface? = null
    override fun init(savedInstanceState: Bundle?) {
        btn_jw.setOnClickListener {
            val intent = Intent(mContext, MyMapActivity::class.java)
            startActivity(intent)
        }
        iv_pic.setOnClickListener {
            getImage()

        }
        flat_action.setOnClickListener {
            if (exif == null) {
                return@setOnClickListener
            }
            saveAction()
        }
        et_gps_date.setOnClickListener {
            val calendar = Calendar.getInstance()

            val datePicker = DatePickerDialog.newInstance(
                { view, year, monthOfYear, dayOfMonth ->
                    val month = monthOfYear + 1
                    var monthSt = month.toString()
                    if (month < 10) {
                        monthSt = "0$month"
                    }
                    var daySt = dayOfMonth.toString()
                    if (dayOfMonth < 10) {
                        daySt = "0$dayOfMonth"
                    }
                    val timeYear = "$year:$monthSt:$daySt"
                    et_gps_date.text = timeYear
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            datePicker.show(supportFragmentManager, "et_gps_date")
        }
        et_gps_time.setOnClickListener {
            if (et_gps_date.text.toString().isNullOrEmpty()) {
                ToastUtils.show("请先选择GPS日期戳")
                return@setOnClickListener
            }
            val calendar = Calendar.getInstance()
            TimePickerDialog.newInstance(
                { view, hourOfDay, minute, second ->
                    var hday = hourOfDay.toString()
                    if (hourOfDay < 10) {
                        hday = "0$hourOfDay"
                    }
                    var minS = minute.toString()
                    if (minute < 10) {
                        minS = "0$minute"
                    }
                    var secondS = second.toString()
                    if (second < 10) {
                        secondS = "0$second"
                    }
                    et_gps_time.text = "$hday:$minS:$secondS"
                },

                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                calendar.get(Calendar.SECOND),
                true
            ).show(supportFragmentManager, "et_gps_time")
        }

        et_date.setOnClickListener {
            val calendar = Calendar.getInstance()

            val datePicker = DatePickerDialog.newInstance(
                { view, year, monthOfYear, dayOfMonth ->
                    val month = monthOfYear + 1
                    var monthSt = month.toString()
                    if (month < 10) {
                        monthSt = "0$month"
                    }
                    var daySt = dayOfMonth.toString()
                    if (dayOfMonth < 10) {
                        daySt = "0$dayOfMonth"
                    }
                    val timeYear = "$year:$monthSt:$daySt"
                    showTimeDate(calendar, timeYear)
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            datePicker.show(supportFragmentManager, "et_date")
        }

        flat_save_action.setOnClickListener {
            //保存模板
            saveTemplate()

        }
        flat_install_action.setOnClickListener {
            //填充模板
            loadTemplate()
        }
        flat_edit_action.setOnClickListener {
            //编辑模板
            val intent = Intent(mContext, TemplateActivity::class.java)
            startActivity(intent)
        }
    }

    private fun changeTimes(times: String, secondS: String) {

        val calendar = Calendar.getInstance()
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        sdf.timeZone = TimeZone.getTimeZone("GMT-8")
        val date = TimeUtils.string2Date(times, sdf)
        calendar.time = date
        val timeYear = getTimeYear(calendar)
        val timeDate = getTimeDate(calendar, secondS)
        et_gps_date.text = timeYear
        et_gps_time.text = timeDate
    }

    private fun getTimeDate(calendar: Calendar, secondS: String): String {
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val seconds = calendar.get(Calendar.MILLISECOND)
        var hday = hour.toString()
        if (hour < 10) {
            hday = "0$hour"
        }
        var minS = minute.toString()
        if (minute < 10) {
            minS = "0$minute"
        }
//        var secondS = seconds.toString()
//        if (seconds < 10) {
//            secondS = "0$seconds"
//        }
        return "$hday:$minS:$secondS"
    }

    private fun getTimeYear(calendar: Calendar): String {
        val year = "${calendar.get(Calendar.YEAR) }"
        val month = calendar.get(Calendar.MONTH) + 1
        val dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) - 1
        var monthSt = month.toString()
        if (month < 10) {
            monthSt = "0$month"
        }
        var daySt = dayOfMonth.toString()
        if (dayOfMonth < 10) {
            daySt = "0$dayOfMonth"
        }
        return "$year:$monthSt:$daySt"
    }

    private fun saveTemplate() {
        val make = et_make.text.toString()
        val mode = et_mode.text.toString()
        val gpsDate = et_gps_date.text.toString()
        val time = et_gps_time.text.toString()
        val alt = et_gps_alt.text.toString()
        val date = et_date.text.toString()
        val expTime = et_exp_time.text.toString()
        val flash = et_flash.text.toString()
        val focal = et_focal.text.toString()
        val orien = et_orien.text.toString()
        val blance = et_balance.text.toString()
        val exifEntity = ExifTemplateEntity(
            make,
            mode,
            gpsDate,
            time,
            alt,
            date,
            expTime,
            flash,
            focal,
            orien,
            blance
        )
        mainKv.encode(JSON_EXIF, Gson().toJson(exifEntity))
        ToastUtils.show("保存成功！")
    }

    private fun loadTemplate() {
        val exifEntityJson = mainKv.decodeString(JSON_EXIF, "")
        if (exifEntityJson.isNotEmpty()) {
            val entity =
                Gson().fromJson<ExifTemplateEntity>(exifEntityJson, ExifTemplateEntity::class.java)
            if (entity != null) {
                et_make.text = Editable.Factory.getInstance().newEditable(entity.make)
                et_mode.text = Editable.Factory.getInstance().newEditable(entity.mode)
                val gpsDate = entity.gpsDate
                if (gpsDate != null && gpsDate.isNotEmpty()) {
                    et_gps_date.text = gpsDate
                }
                val gpsTime = entity.time
                if (gpsTime != null && gpsTime.isNotEmpty()) {
                    et_gps_time.text = gpsTime
                }
                et_gps_alt.text = Editable.Factory.getInstance().newEditable(entity.alt)
                val date = entity.date
                if (date != null && date.isNotEmpty()) {
                    et_date.text = date
                }
                et_exp_time.text = Editable.Factory.getInstance().newEditable(entity.expTime)
                et_flash.text = Editable.Factory.getInstance().newEditable(entity.flash)
                et_focal.text = Editable.Factory.getInstance().newEditable(entity.focal)
                et_orien.text = Editable.Factory.getInstance().newEditable(entity.orien)
                et_balance.text = Editable.Factory.getInstance().newEditable(entity.blance)
            }
        }
    }

    private fun showTimeDate(calendar: Calendar, timeYear: String) {
        TimePickerDialog.newInstance(
            { view, hourOfDay, minute, second ->
                var hday = hourOfDay.toString()
                if (hourOfDay < 10) {
                    hday = "0$hourOfDay"
                }
                var minS = minute.toString()
                if (minute < 10) {
                    minS = "0$minute"
                }
                var secondS = second.toString()
                if (second < 10) {
                    secondS = "0$second"
                }
                val timeShow = "$timeYear $hday:$minS:$secondS"
                et_date.text = timeShow
                val cstTime = "${timeYear.replace(":", "-")} $hday:$minS:$secondS"
                changeTimes(cstTime, secondS)
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            calendar.get(Calendar.SECOND),
            true
        ).show(supportFragmentManager, "et_date")
    }

    private fun saveAction() {
        val make = et_make.text.toString()
        val mode = et_mode.text.toString()
        val gpsDate = et_gps_date.text.toString()
        val time = et_gps_time.text.toString()
        val alt = et_gps_alt.text.toString()
        val date = et_date.text.toString()
        val expTime = et_exp_time.text.toString()
        val flash = et_flash.text.toString()
        val focal = et_focal.text.toString()
        val orien = et_orien.text.toString()
        val blance = et_balance.text.toString()
        try {
            exif?.setAttribute(ExifInterface.TAG_MAKE, make)
            exif?.setAttribute(ExifInterface.TAG_MODEL, mode)
            exif?.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, gpsDate)
            exif?.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, time)
            exif?.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, alt)
            exif?.setAttribute(ExifInterface.TAG_DATETIME, date)
            exif?.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, expTime)
            exif?.setAttribute(ExifInterface.TAG_FLASH, flash)
            exif?.setAttribute(ExifInterface.TAG_FOCAL_LENGTH, focal)
            exif?.setAttribute(ExifInterface.TAG_ORIENTATION, orien)
            exif?.setAttribute(ExifInterface.TAG_WHITE_BALANCE, blance)
            if (clickLatLng != null) {
                exif?.setLatLong(clickLatLng?.latitude!!, clickLatLng?.longitude!!)
            }
            exif?.saveAttributes()
            readImageInfo()
            ToastUtils.show("保存成功！")
        } catch (e: IOException) {
            e.printStackTrace();
        }
    }

    private fun getImage() {
        RxPermissions(this).request(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
        )
            .subscribe() {
                if (it) {
                    PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .isSingleDirectReturn(true)
                        .selectionMode(PictureConfig.SINGLE)
                        .imageEngine(GlideEngine)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: MutableList<LocalMedia>?) {
                                val realPath = result?.get(0)?.realPath.toString()
                                iv_pic.load(realPath)
                                exif = logImageInfo(realPath)
                                readImageInfo()
                            }

                            override fun onCancel() {
                            }

                        })
                }
            }

    }

    private fun readImageInfo() {
        val lang = exif?.latLong
        val lat = lang?.get(0)
        val long = lang?.get(1)
        iv_add_info.text = "经度：$long/纬度：$lat"
        et_make.text =
            Editable.Factory.getInstance().newEditable(getString(exif, ExifInterface.TAG_MAKE))
        et_mode.text =
            Editable.Factory.getInstance().newEditable(getString(exif, ExifInterface.TAG_MODEL))
        val gpsDate = getString(exif, ExifInterface.TAG_GPS_DATESTAMP)
        if (gpsDate.isNotEmpty()) {
            et_gps_date.text = gpsDate
        }
        val gpsTime = getString(exif, ExifInterface.TAG_GPS_TIMESTAMP)
        if (gpsTime.isNotEmpty()) {
            et_gps_time.text = gpsTime
        }


        et_gps_alt.text = Editable.Factory.getInstance()
            .newEditable(getString(exif, ExifInterface.TAG_GPS_ALTITUDE))
        val date = getString(exif, ExifInterface.TAG_DATETIME)
        if (date.isNotEmpty()) {
            et_date.text = date
        }
        et_exp_time.text = Editable.Factory.getInstance()
            .newEditable(getString(exif, ExifInterface.TAG_EXPOSURE_TIME))
        et_flash.text =
            Editable.Factory.getInstance().newEditable(getString(exif, ExifInterface.TAG_FLASH))
        et_focal.text = Editable.Factory.getInstance()
            .newEditable(getString(exif, ExifInterface.TAG_FOCAL_LENGTH))
        et_orien.text = Editable.Factory.getInstance()
            .newEditable(getString(exif, ExifInterface.TAG_ORIENTATION))
        et_balance.text = Editable.Factory.getInstance()
            .newEditable(getString(exif, ExifInterface.TAG_WHITE_BALANCE))
    }

    private fun getString(exif: ExifInterface?, type: String): String {
        return exif?.getAttribute(type).toString()
    }

    override fun loadData() {
        RxEventBus.getInstance().toObservable(MapEvent::class.java)
            .subscribe(object : SugarHandleSubscriber<MapEvent>() {
                override fun onNext(t: MapEvent) {
                    clickLatLng = t.latlng
                    info.text = "选择地址的经纬度：" + clickLatLng?.latitude + "/" + clickLatLng?.longitude
                }

            })
    }

    override fun getContentView(): Int {
        return R.layout.activity_main
    }


}